using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace OrigPacman
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        #region Global variables
        GraphicsDeviceManager graphics;

        KeyPress.KeyPressGame keys;

        // Starts with 3 lives
        Pacman pacman;
        
        List<Waypoint> waypoints = null;

        // Audio variables
        AudioEngine audioEngine;
        WaveBank waveBank;
        SoundBank soundBank;

        #region ghost data
        Dictionary<Ghost.Color, Texture2D> ghostTextures;
        List<Ghost> ghostList;
        Random rand;

        /// tells whether or not to flash the ghosts color
        /// for when super mode is almost over
        bool flashGhost = false;
        /// tells whether the super power is almost over
        bool superAlmostOver = false;
        #endregion

        Map map;
        SpriteBatch sprite;
        Score score;
        #endregion

        #region Constants
        // start flashing the ghosts when this amount
        // of time is left in pacman super mode
        private const float FlashGhostsTime = 2.0f;
        #endregion

        #region Properties
        public bool SuperAlmostOver
        {
            get { return superAlmostOver; }
        }

        public bool FlashGhost
        {
            get { return flashGhost; }
        }

        public Pacman Player
        {
            get { return pacman; }
            set { pacman = value; }
        }
        public List<Ghost> NonPlayableCharacters
        {
            get { return ghostList; }
            set { ghostList = value; }
        }
        public Score Score
        {
            get { return score; }
            set { score = value; }
        }

        /// <summary>
        /// the list of ghosts
        /// </summary>
        public List<Ghost> GhostList
        {
            get { return ghostList; }
            set { ghostList = value; }
        }

        /// <summary>
        /// the list of waypoints
        /// </summary>
        public List<Waypoint> Waypoints
        {
            get { return waypoints; }
            set { waypoints = value; }
        }

        /// <summary>
        /// the ghost textures dictionary
        /// </summary>
        public Dictionary<Ghost.Color, Texture2D> GhostTextures
        {
            get { return ghostTextures; }
            set { ghostTextures = value; }
        }
        #endregion

        #region game methods
        public Game1()
        {
            pacman = new Pacman(this);

            graphics = new GraphicsDeviceManager(this);

            keys = new KeyPress.KeyPressGame();

            map = new Map(graphics.GraphicsDevice);
            pacman.SetStartingPacmanWaypoints(map.Waypoints);
            
            ghostList = new List<Ghost>();
            ghostList.Add(new Ghost(Ghost.Color.BLUE, new Vector2(100, 100), this));
            ghostList.Add(new Ghost(Ghost.Color.GREEN, new Vector2(200, 200), this));
            ghostList.Add(new Ghost(Ghost.Color.ORANGE, new Vector2(300, 300), this));
            ghostList.Add(new Ghost(Ghost.Color.RED, new Vector2(400, 400), this));
            pacman.SetGhostPoints();
            ghostTextures = new Dictionary<Ghost.Color, Texture2D>();
            
            rand = new Random();
            SetWaypoints(map.Waypoints);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            score = new Score();
            audioEngine = new AudioEngine("audio/pacmanAudio.xgs");
            waveBank = new WaveBank(audioEngine, "audio/Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, "audio/Sound Bank.xsb");
            pacman.Sounds = soundBank;

            soundBank.PlayCue("start");

            base.Initialize();
        }

        /// <summary>
        /// Load your graphics content.  If loadAllContent is true, you should
        /// load content from both ResourceManagementMode pools.  Otherwise, just
        /// load ResourceManagementMode.Manual content.
        /// </summary>
        /// <param name="loadAllContent">Which type of content to load.</param>
        protected override void LoadContent()
        {
            sprite = new SpriteBatch(graphics.GraphicsDevice);
            // TODO: Load any ResourceManagementMode.Automatic content
            pacman.Textures.Add(Content.Load<Texture2D>("images/PacmanUp"));
            pacman.Textures.Add(Content.Load<Texture2D>("images/PacmanDown"));
            pacman.Textures.Add(Content.Load<Texture2D>("images/PacmanRight"));
            pacman.Textures.Add(Content.Load<Texture2D>("images/PacmanLeft"));
            pacman.DeathAnimation = Content.Load<Texture2D>("images/deathAnim");
            pacman.DeathAnimation.Name = "Death";
            pacman.Texture = pacman.Textures[(int)Direction.EAST];
            map.LoadContent(Content);
            ghostTextures.Add(Ghost.Color.RED, Content.Load<Texture2D>("images/red"));
            ghostTextures.Add(Ghost.Color.BLUE, Content.Load<Texture2D>("images/blue"));
            ghostTextures.Add(Ghost.Color.ORANGE, Content.Load<Texture2D>("images/orange"));
            ghostTextures.Add(Ghost.Color.GREEN, Content.Load<Texture2D>("images/green"));
            ghostTextures.Add(Ghost.Color.WHITE, Content.Load<Texture2D>("images/white"));
            // TODO: Load any ResourceManagementMode.Manual content
            score.Font = Content.Load<SpriteFont>("Times New Roman");
        }

        /// <summary>
        /// Unload your graphics content.  If unloadAllContent is true, you should
        /// unload content from both ResourceManagementMode pools.  Otherwise, just
        /// unload ResourceManagementMode.Manual content.  Manual content will get
        /// Disposed by the GraphicsDevice during a Reset.
        /// </summary>
        /// <param name="unloadAllContent">Which type of content to unload.</param>
        protected override void UnloadContent()
        {
            Content.Unload();
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the default game to exit on Xbox 360 and Windows
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            // The time since Update was called last
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            KeyPress.KeyPressGame.UpdateInput(elapsed);
            if (wasEscapePressed() == false)
            {
                // TODO: Add your game logic here
                UpdateGhosts(elapsed, pacman);
                pacman.UpdatePacman(elapsed);
                map.Update(elapsed, pacman);
                score.Update(pacman);
                if (map.Complete)
                {
                    score.Complete = true;
                    pacman.Alive = false;
                }
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            sprite.Begin(SpriteBlendMode.AlphaBlend);

            map.Render(ref sprite);
            pacman.RenderPacman(ref sprite);
            RenderGhosts(ref sprite);
            RenderScore(ref sprite);
            sprite.End();

            base.Draw(gameTime);
        }

        /// <summary>
        /// updating each ghost by calling ghost update method from ghost.cs
        /// </summary>
        /// <param name="elapsed">elapsed time</param>
        /// <param name="pacman">pacman</param>
        public void UpdateGhosts(float elapsed, Pacman pacman)
        {
            foreach (Ghost theGhost in ghostList)
            {
                if (!theGhost.Alive)
                {
                    //theGhost.Position = map.Waypoints[0].Position;
                    theGhost.Alive = true;
                    theGhost.Reset(waypoints);
                }
                theGhost.UpdateGhost(elapsed, pacman, rand);
            }
        }

        /// <summary>
        /// rendering each ghost by calling ghost render method from ghost.cs
        /// </summary>
        /// <param name="sprite"></param>
        public void RenderGhosts(ref SpriteBatch sprite)
        {
            if (pacman.SuperTime < FlashGhostsTime)
            {
                superAlmostOver = true;
                flashGhost = !flashGhost;
            }
            else
            {
                superAlmostOver = false;
                flashGhost = false;
            }

            foreach (Ghost theGhost in ghostList)
            {
                theGhost.RenderGhost(ref sprite);
            }
        }

        /// <summary>
        /// set waypoints for each ghost by calling set waypoints method from ghost.cs
        /// </summary>
        /// <param name="list"></param>
        void SetWaypoints(List<Waypoint> list)
        {
            foreach (Ghost theGhost in ghostList)
            {
                theGhost.SetWaypoint(list);
            }
        }

        private bool wasEscapePressed()
        {
            if (KeyPress.KeyPressGame.KeyPressedThisFrame(Keys.Escape))
            {
                this.Exit();
                return true;
            }
            return false;
        }

        private void RenderScore(ref SpriteBatch sprite)
        {
            score.Draw(ref sprite);
        }

        public void EndGame()
        {
            while (true)
            {
                // sit here and never do anything again ...
                sprite.Begin(SpriteBlendMode.AlphaBlend);
                score.Draw(ref sprite);
                sprite.End();
            }
        }
        #endregion
    }
}